import { useState, useEffect } from 'react';

interface MobileInfo {
  device: string;
  os: string;
  browser: string;
  isMobile: boolean;
  memory?: number | string;
}

function getMobileInfo(): MobileInfo {
  const ua = navigator.userAgent;
  let device = '未知设备';
  let os = '未知系统';
  let browser = '未知浏览器';
  let isMobile = /Mobile|Android|iPhone|iPad|iPod|Windows Phone/i.test(ua);

  // 判断设备类型
  if (/Android/i.test(ua)) device = 'Android';
  else if (/iPhone|iPad|iPod/i.test(ua)) device = 'iOS';
  else if (/Windows Phone/i.test(ua)) device = 'Windows Phone';
  else if (/Macintosh/i.test(ua)) device = 'Mac';
  else if (/Windows/i.test(ua)) device = 'Windows';

  // 判断操作系统
  if (/Android/i.test(ua)) os = 'Android';
  else if (/iPhone|iPad|iPod/i.test(ua)) os = 'iOS';
  else if (/Windows Phone/i.test(ua)) os = 'Windows Phone';
  else if (/Windows NT/i.test(ua)) os = 'Windows';
  else if (/Mac OS/i.test(ua)) os = 'Mac OS';

  // 判断浏览器
  if (/MicroMessenger/i.test(ua)) browser = '微信浏览器';
  else if (/QQBrowser/i.test(ua)) browser = 'QQ浏览器';
  else if (/Chrome/i.test(ua)) browser = 'Chrome';
  else if (/Safari/i.test(ua)) browser = 'Safari';
  else if (/Firefox/i.test(ua)) browser = 'Firefox';
  else if (/MSIE|Trident/i.test(ua)) browser = 'IE';

  const memory = (navigator as any).deviceMemory || '未知';
  return { device, os, browser, isMobile, memory };
}

export function useMobileInfo() {
  const [info, setInfo] = useState<MobileInfo>({ device: '', os: '', browser: '', isMobile: false });

  useEffect(() => {
    setInfo(getMobileInfo());
  }, []);

  return info;
}